<?php

namespace app\admin\controller;


class Category extends Common
{
    private $db;
    public function __construct()
    {
        parent::__construct();
        $this->db = new \app\common\model\Category();
    }
    //首页
    public function index(){
        $cateData = $this->db->getCateData();
        $this->assign('cateData',$cateData);
        return view();
    }
    //添加
    public function add(){
        if(request()->isPost()){
            $res = $this->db->add(input('post.'));
            if ($res['valid']){
                $this->success($res['msg'],'admin/category/index');
            }else{
                $this->error($res['msg']);
            }
        }
        return view();
    }
    //添加子分类  子分类的pid就是父级分类的cid
    public function addSon(){
        //处理页面所属分类
        $cid = input('param.cid');
        $cateData = db('category')->field(['cid','cname'])->find($cid);
        $this->assign('cateData',$cateData);

        //执行添加子分类
        if(request()->isPost()){
            $res = $this->db->add(input('post.'));
            if ($res['valid']){
                $this->success($res['msg'],'admin/category/index');
            }else{
                $this->error($res['msg']);
            }
        }
        return view();
    }

    public function del(){
        $cid = input('param.cid');
        $res = $this->db->del($cid);
        if ($res['valid']) {
            $this->success($res['msg'], 'admin/category/index');
        } else {
            $this->error($res['msg']);
        }
    }
    public function edit(){
        $cid = input('param.cid');
        //2.获取旧数据
        $oldData = db('category')->find($cid);
        $this->assign('oldData',$oldData);
        //3.处理所属分类
        //通过cid获取自己和自己的子集再除去
        $cateData = $this->db->categoryData($cid);
        //分配变量
        $this->assign('cateData',$cateData);
        //1.载入模板
        return view();
    }
}
